from . import api
from ihome.models import Area
from flask import current_app,jsonify
from ihome.utils.response_code import RET


# 定义全局变量area_li,用来存储查询出来的所有城区信息
area_li = None
# GET http://127.0.0.1:5000/api/v1.0/areas
@api.route("/areas")
def get_area_info():
    """查询所有城区信息"""
    try:
        global area_li # 声明当前使用全局变量
        if area_li is None:
            area_li = Area.query.all()
            print("从Mysql数据库中查询到城区信息")
        else:
            print("从全局变量中获取城区信息")

        print("area_li=", area_li, ",type=", type(area_li))

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="数据库异常")

    area_dict_li = []

    for area in area_li:
        # area_dict = {
        #     "aid":area.id,
        #     "aname":area.name
        # }
        area_dict_li.append(area.to_dict())

    return jsonify(errno=RET.OK,errmsg="OK",data=area_dict_li)









